package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;
import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //发送短信验证码并保存验证码
        //1.校验手机号是否正确
        if (StringUtils.isNotBlank(phone)) {
            if (RegexUtils.isPhoneInvalid(phone)){
                return Result.fail("输入的手机号格式有误！");
            }else {
                //2.获取验证码
                String code = RandomUtil.randomNumbers(6);
                //3.将验证码保存到redis中，并设置手机号为key
                String codeKey = LOGIN_CODE_KEY + phone;
                stringRedisTemplate.opsForValue().set(codeKey,code,60, TimeUnit.SECONDS);
                //4.发送验证码
                log.info("向"+phone+"发送验证码："+code);
            }
        }
        //5.响应成功信息
        return Result.ok("成功！");
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号码格式
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())){
            return Result.fail("输入的手机号格式有误！");
        }
        //2.获取并校验验证码
        String code = loginForm.getCode();
        //从redis中获取验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        if (StringUtils.isBlank(code) || !code.equals(cacheCode)){
            return Result.fail("验证码有误！");
        }
        //3.查询用户是否存在
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, loginForm.getPhone()));
        if (user == null){
            //3-1若用户不存在，则创建用户
            user =  createUserWithPhone(loginForm.getPhone());
        }
        //4.生成token,作为登陆令牌
        String token = UUID.randomUUID().toString(true);
        //5.将用户信息转换为map存入redis中
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                                    .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //6.设置用户信息有效期
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.MINUTES);
        //7.返回token到前台
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //1.获取登陆用户ID
        Long id = UserHolder.getUser().getId();
        //2.获取当前日期并格式化为:yyyyMM
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //3.拼接获取前缀
        String key = USER_SIGN_KEY + id + keySuffix;
        //4.获取当前日期是本月的第几天
        int dayOfMonth = now.getDayOfMonth() - 1;
        //5.使用bitMap完成签到
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1.获取当前登陆用户ID
        Long id = UserHolder.getUser().getId();

        //2.获取当前日期在本月的第几天
        LocalDateTime now = LocalDateTime.now();
        int dayOfMonth = now.getDayOfMonth();

        //3.拼接获取key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + id + keySuffix;

        //4.通过bitField key uDayOfMonth 0获取本月截止今天为止的所有的签到记录，返回的是一个十进制的数字
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        //5.统计连续签到数
        if (result == null || result.isEmpty()){
            //没有任何签到结果
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0){
            return Result.ok(0);
        }

        int count = 0;
        while (true){
            //将获取的十进制签到记录与1进行"与运算" ===> 将十进制数化为二进制数 然后从最右边往最左一直做"与"运算，然后把数字右移一位，抛弃最后一个bit位，继续下一个bit位 碰到0就结束
            //例如：23->10111 10111&1=1 1011&1=1 101&1=1 10&1=0结束
            if ((num & 1) == 0){
                //碰到0 表示连续签到中断 结束
                break;
            }else {
                count++;
            }
            num>>>=1;
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
